//
//  ComposeViewController.swift
//  weibo
//
//  Created by 陈伟 on 15/10/25.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
   
    private lazy var emoticonView: EmoticonView = EmoticonView { (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    //toolbar按钮点击事件
    @objc func clickBarBtn() {
        
    }
    
    @objc func selectEmoticon() {
//        print("选择表情")
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        textView.becomeFirstResponder()
    }
    
    @objc private func keyboardChanged(n: NSNotification) {
//        print(n)
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    override func loadView() {
        super.loadView()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        textView.becomeFirstResponder()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func setupUI() {
        prepareNavigation()
        prepareToolBar()
        prepareTextView()
    }
    
    private lazy var toolBar = UIToolbar()
    
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        //滚动
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel =  {
        
        let lb = UILabel(title: "分享新鲜事...", fontsize: 18, color: UIColor.lightGrayColor())
        return lb
    }()
    
    @objc func clickClose() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func clickSend() {
        NetworkTools.sharedTools.composeStatus("lala") { (result, error) -> () in
            if error != nil {
                print(error)
            }
            print(result)
        }
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //准备toolBar
    func prepareToolBar() {
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items  = [UIBarButtonItem]()

        for dict in itemSettings {
            
            let barBtn = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(barBtn)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
            
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
    }
    //准备textView
    func prepareTextView(){
        view.addSubview(textView)
        view.addSubview(placeHolderLabel)
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    //准备导航条
    func prepareNavigation() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "quxiao", style: UIBarButtonItemStyle.Plain, target: self, action: "clickClose")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "clickSend")
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发微博", fontsize: 15, color: UIColor.blackColor())
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.screen_name ?? "", fontsize: 13)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        navigationItem.titleView = titleView
    }
}

extension  ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem!.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}
